/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cross;

import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mateusz.ledzewicz
 */
public class CrossObject extends Thread{
    public ArrayList<CarThread> cars;
    public int count = 0;
    public boolean free = true;
    public CrossObject(int numbersOfCars){
        cars = new ArrayList();
        Random rnd = new Random();
        for(int i=0;i<numbersOfCars;i++){
            CarThread car = new CarThread(rnd.nextInt(1000), this);
            cars.add(car);
            car.start();
        }
    }
        
    public synchronized void  driveOut(CarThread car){
        car.move();
        free = true;
        car.log("DriveOut");
    }
    
    public synchronized void increaseCounter(){
        this.count++;
    }
    
    public synchronized void decreaseCounter(){
        this.count--;
    }
    
    
    @Override
   public void run(){
       while(true){
          synchronized (this) {
                if(this.count > 0 && this.free){
                    System.out.println("Notify " + count);
                    this.notify();
                    this.decreaseCounter();
                    this.free = false;
               }
          }
       }
   }
    
    public ArrayList<CarThread> getCars(){
        return this.cars;
    }
}
